package com.lucy.common.validator;


import com.google.common.collect.Lists;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;


@Slf4j
public class IsEnumValidator implements ConstraintValidator<IsEnum, Object> {
    private final List<Object> values = Lists.newArrayList();


    @Override
    public void initialize(IsEnum constraintAnnotation) {

        Class<?> enumClazz = constraintAnnotation.value();
        Object[] enumConstants = enumClazz.getEnumConstants();
        if (null == enumConstants) {
            return;
        }
        Method method = BeanUtils.findMethod(enumClazz, constraintAnnotation.method());
        if (null == method) {
            log.warn("枚举对象:[{}]中不存在方法:[{}],请检查.", enumClazz.getName(), constraintAnnotation.method());
            throw new BusinessException(HttpStatus.BAD_REQUEST,"枚举对象中不存在获取值的方法");
        }

        method.setAccessible(true);
        try {
            for (Object enumConstant : enumConstants) {
                values.add(method.invoke(enumConstant));
            }
        } catch (IllegalAccessException | InvocationTargetException e) {
            log.warn("获取枚举类:[{}]的枚举对象的值失败.", enumClazz);
            throw new BusinessException(HttpStatus.BAD_REQUEST,"获取枚举值失败");
        }
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return null == value || values.contains(value);
    }
}
